package control

import (
	"encoding/base64"
	"encoding/hex"
	"net/http"
	"strconv"
	"time"

	"github.com/lerryxiao/gin"
	"hiscene.com/openplatform/common/logger"
)

//////////////////////////////////////////////////////////////////////////////////////

const (
	encodeDefine       = "gfedcbahijklZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponm!^$1357908-_"
	expireTime   int64 = 5 * 60
)

var (
	b64Encoding = base64.NewEncoding(encodeDefine).WithPadding(base64.NoPadding)
)

//////////////////////////////////////////////////////////////////////////////////////

func gainSession() string {
	src := make([]byte, 0)
	src = strconv.AppendInt(src, time.Now().Unix(), 10)
	dst := make([]byte, hex.EncodedLen(len(src)))
	hex.Encode(dst, src)
	return b64Encoding.EncodeToString(dst)
}

func checkSession(session string) bool {
	hexs, err := b64Encoding.DecodeString(session)
	if err != nil {
		logger.Log4g.Error("check session: %v, base64 decode error: %v", session, err)
		return false
	}
	dst := make([]byte, hex.DecodedLen(len(hexs)))
	nlen, err := hex.Decode(dst, hexs)
	if err != nil {
		logger.Log4g.Error("check session: %v, hex decode error: %v, len: %v", session, err, nlen)
		return false
	}
	tm, err := strconv.ParseInt(string(dst), 10, 64)
	if err != nil {
		logger.Log4g.Error("check session: %v, parse int error: %v", session, err)
		return false
	}
	ntm := time.Now().Unix()
	if tm > ntm || ntm-tm > expireTime {
		logger.Log4g.Error("check session: %v failed, session time: %v, now time: %v, expire time: %v", session, tm, ntm, ntm-tm)
		return false
	}
	return true
}

//////////////////////////////////////////////////////////////////////////////////////
func pageIndex(context *gin.Context) {
	context.HTML(http.StatusOK, "index.html", nil)
}

func pageLampList(c *gin.Context) {
	c.HTML(http.StatusOK, "lampList.html", gin.H{"sessionKey": gainSession()})
}

func pageLampOnOff(c *gin.Context) {
	c.HTML(http.StatusOK, "lampOnOff.html", gin.H{"sessionKey": gainSession()})
}

func pageBoardList(c *gin.Context) {
	c.HTML(http.StatusOK, "boardList.html", gin.H{"sessionKey": gainSession()})
}

//////////////////////////////////////////////////////////////////////////////////////
